<template>
  <el-pagination
    class="paging"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page.sync="currentPage"
    :page-size="size"
    :total="total"
    :page-sizes="pagesSizes"
    :pager-count="5"
    :layout="layout"
  ></el-pagination>
</template>

<script>
  import { mapActions } from 'vuex';
  export default {
    name: 'paging-component',
    props: {
      func: {
        type: Function,
      },
      layout: {
        type: String,
        default: 'total, sizes, prev, pager, next,jumper, ->',
      },
      sizeNum: {
        type: Number,
        default: 10,
      },
      pagesSizes: {
        type: Array,
        default: () => {
          return [5, 10, 20, 30, 50];
        },
      },
    },
    data() {
      return {
        size: this.sizeNum,
        currentPage: 1,
        tempPage: 1,
        total: 0,
        position: 'right',
      };
    },
    watch: {
      sizeNum(value) {
        console.log(value);
        this.size = value;
      },
    },
    mounted() {
      this.setPaging({ size: this.size, num: this.tempPage });
    },
    methods: {
      ...mapActions({
        setPaging: 'user/setPaging',
      }),
      refresh() {
        this.search(this.tempPage);
      },
      handleSizeChange(size) {
        console.log(size);
        this.size = size;
        this.tempPage = 1;
        this.setPaging({ size: this.size, num: this.tempPage });
        this.refresh();
      },
      handleCurrentChange(current) {
        console.log(current);
        this.tempPage = current;
        this.setPaging({ size: this.size, num: this.tempPage });
        this.refresh();
      },
      search(currentPage = 1) {
        if (this.func) {
          this.tempPage = currentPage;
          this.setPaging({ size: this.size, num: this.tempPage });
          this.func(this.setResultCallback);
        }
      },
      setResultCallback(records, recordCount) {
        if (records.length == 0 && this.currentPage > 1) this.search(--this.currentPage);
        else {
          this.total = recordCount;
          this.currentPage = this.tempPage; //这里可能会出现bug，当前页应该根据total来设置，这里存在本地是为了实现返回时能到之前的页面，实际上可能已经没有这么多页数了
        }
      },
    },
  };
</script>

<style lang="less" scoped>
  .paging {
    background: #fff;
    border-radius: 4px;
    height: 50px;
    text-align: center !important;
    padding: 10px 0;
  }
</style>
